package team.first.movieapiv2pro.dao.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import dev.morphia.Datastore;
import org.springframework.stereotype.Repository;
import team.first.movieapiv2pro.dao.CommentDAO;
import team.first.movieapiv2pro.doc.CommentDoc;
import team.first.movieapiv2pro.util.MongoDBUtil;

import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2pro.dao.impl
 * @Date: 2021/12/26 9:36
 * @Description:
 */
@Repository
public class CommentDAOImpl implements CommentDAO {

    @Override
    public List<DBObject> selectMovieComment(Integer movieId) {
        DBCollection movieCollection = MongoDBUtil.getCollection("comment");
        // 建立查询条件
        BasicDBObject filter_dbobject = new BasicDBObject();
        filter_dbobject.put("movieId", movieId);
        // 条件查询
        DBCursor cursor1 = movieCollection.find(filter_dbobject).sort(new BasicDBObject("id", 1));

        // 将结果转为集合
        return cursor1.toArray();
    }

    @Override
    public boolean insertComment(CommentDoc commentDoc) {
        try {
            Datastore datastore = MongoDBUtil.getDataStore();
            datastore.getMapper().mapPackage("team.first.movieapiv2pro.doc");
            datastore.save(commentDoc);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
